/*
 * Copyright (C) 拾光分享网 
 * All rights reserved, Designed By www.hiai.top.
 * Email：goodsking@163.com.
 */
package top.hiai.common.account;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.ehcache.CacheKit;
import top.hiai.common.model.User;

import java.util.List;

/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top
* @Introduction 类的介绍
*/
@SuppressWarnings("rawtypes")
public class UserService {

	public static final UserService me = new UserService();
	private User userDao = new User().dao();
	private final String allAccountsCacheName = "allAccounts";
	
	public void join(String joinOnField, List<? extends Model> modelList, String... joinAttrs) {
		if (modelList != null) {
			for (Model m : modelList) {
				join(joinOnField, m, joinAttrs);
			}
		}
	}

	/**
	 * 需要关联查询获取 Account 对象的 nickName、avatar 时使用此方法
	 * 避免使用关联查询，优化性能，在使用中更关键的地方在于缓存的清除
	 * @param joinOnField join 使用的字段名，account 这端使用 id
	 * @param model 需要 join 的 model
	 * @param joinAttrs 需要 join 到 model 中的的属性名称
	 */
	public void join(String joinOnField, Model model, String... joinAttrs) {
		Integer accountId = model.getInt(joinOnField);
		if (accountId == null) {
			throw new RuntimeException("Model 中的 \"" + joinOnField  + "\" 属性值不能为 null");
		}

        User account = getById(accountId);

        // join 真正开始的地方，前面是准备工作
		if (account != null) {
			for (String attr : joinAttrs) {
				model.put(attr, account.get(attr));
			}
		} else {
			throw new RuntimeException("未找到 account 或者 account 状态不合法，account 的 id 值为：" + accountId + " 可能是数据库数据不一致");
		}
	}
	
    /**
     * 优先从缓存中获取 account 对象，可获取到被 block 的 account
     */
    public User getById(int accountId) {
        // 优先从缓存中取，未命中缓存则从数据库取
        User account = CacheKit.get(allAccountsCacheName, accountId);
        if (account == null) {
            // 考虑到可能需要 join 状态不合法的用户，先放开 status 的判断
            // account = dao.findFirst("select * from account where id=? and status=? limit 1", accountId, Account.STATUS_OK);
            account = userDao.findFirst("select * from bbs_user where uid=? limit 1", accountId);
            if (account != null) {
                account.removeSensitiveInfo();
                CacheKit.put(allAccountsCacheName, accountId, account);
            }
        }
        return account;
    }
    
	/**
	 * 通过nickName获取Account对象，仅返回指定的字段，多字段用逗号分隔
	 */
	public User getByNickName(String nickName, String columns) {
		if (StrKit.isBlank(nickName)) {
			return null;
		}
		return userDao.findFirst("select " + columns +" from bbs_user where nickName=?  and status=?  limit 1", nickName, User.STATUS_OK);
	}
	
}